<?php

namespace app\backend\controller;

use app\backend\library\DataController;
use app\backend\validator\AddProductValidator;
use app\backend\validator\UpdProductValidator;
use app\common\model\Product as ProductModel;

class Product extends DataController
{
    protected $mdl = ProductModel::class;

    protected $excludeMainFields = ['is_deleted', 'deleted_at'];

    protected $allowSortFields = [
        'id',
        'status',
        'aid',
        'cate_id',
        'price',
        'amount',
        'created_at',
        'amount_scheme',
        'rand_num',
        'limit_num',
        'remain_num',
    ];

    protected $allowSearchFields = [
        'id',
        'product_name',
        'status',
        'format',
        'aid',
        'cate_id',
        'Manager.username',
        'Category.category_name',
        'created_at',
        'updated_at',
        'proxy',
        'description',
        'flag',
        'sex',
        'amount_scheme',
    ];

    protected $relations = [
        'Manager' => [
            'type' => 'join',
            'alias' => 'a',
            'table' => 'abtm_admin_user',
            'on' => 'abtm_product.aid = a.id',
            'join_type' => 'left',
            'fields' => ['id', 'username']
        ],
        'Category' => [
            'type' => 'join',
            'alias' => 'b',
            'table' => 'abtm_product_category',
            'on' => 'abtm_product.cate_id = b.id',
            'join_type' => 'left',
            'fields' => ['id', 'category_name']
        ]
    ];

    protected function applySearch($query, $params)
    {
        parent::applySearch($query, $params);

        $query->where($this->mainFieldAlias('is_deleted'), $this->mdl::NO_DELETED);
    }

    protected function _printDataHook(&$items)
    {
        $url = env('url.frontend_url');

        foreach ($items as $item) {
            if(!empty($item->pic_url)) {
                $item->pic_url = buildFullUrl($url, 'storage/'. $item->pic_url);
            }
        }
    }

    protected function _saveBeforeHook(&$params)
    {
        if(empty($params['id'])) {
            $this->validate($params, AddProductValidator::class);
        }else{
            $this->validate($params, UpdProductValidator::class);
        }
    }
}